/** @jsxImportSource @emotion/react */
import * as React from "react";
import {Text, LineColumn, InputLine, SuffixInput, TextArea, Input, BlobInputList, InputDatalist, CheckSwitch,
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, useItemInputControl,
} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {useDeleteAddSub} from "../../hook/useDeleteAddSub";

export declare type DefaultCallback = (par: any) => any;
//可以复用的组件： 尽量抽象 和 提高代码复用程度！
interface Props extends InternalItemProps {
    label?: string;
    nos?: string;
    titles?: any[];    //可能是Node[]，不一定纯粹string;
    zjuse?: number;     //最末尾的注释的文本使用那一段话？可选择办法的。
    config?: any[];    //有配置模式的
    /**提供默认值 注入； 仅针对config里面的name字段存储。
     * */
    defValCb?: DefaultCallback;
}
/**分项 开始的概要部分： 支持两列的概况列配置。不能支持3列的模式。
 * */
export const Instrument =
React.forwardRef((
    {children, show, alone = true, refWidth,label,config,redId,nestMd,verId,repId,defValCb}: Props, ref
) => {
    const [surveyItems, itemA设备概况] = React.useMemo(() => {
        const surveyItems = [] as any;          //布局2排的，转为正常的1排列表
        config?.forEach(([[desc, name, cb], add2p]: any, i: number) => {
            const [desc2, name2, cb2] = add2p || [];
            if (typeof name === 'string' && !name?.startsWith('_$')) surveyItems.push({name, desc, cb});
            else if (typeof name === 'object' && name.n && !name.r) surveyItems.push({name: name.n, desc, cb, type: name.t, unit: name.u, list: name.l});
            if (typeof name2 === 'string' && name2 && !name2.startsWith('_$')) surveyItems.push({name: name2, desc: desc2, cb: cb2});
            else if (typeof name2 === 'object' && name2.n && !name2.r) surveyItems.push({name: name2.n, desc: desc2, cb: cb2, type: name2.t, unit: name2.u, list: name2.l});
        });
        const itemA设备概况: string[] = [];
        //初始化 存储字段
        surveyItems.forEach(({name,cb}: any, i: number) => {
            if(cb?.names)   itemA设备概况.push(...cb?.names);
            else  itemA设备概况.push(name);
        });
        return [surveyItems, itemA设备概况];
    }, [config]);

    const [getInpFilter] = useMeasureInpFilter(null, itemA设备概况, defValCb);
    const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
    //若有 备注 必须配置在最后一个的。
    const lastAiObj=surveyItems[surveyItems.length-1];
    const isMemoLast= lastAiObj?.type==='m';
    const toTailNodes: React.ReactNode[]=[];
    const {line}=useDeleteAddSub(nestMd!, redId!,verId!,repId!);
    return (
        <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                             alone={alone}  label={label??'超声波检测-概要仪器'} column={0}>
            {line}
            <LineColumn column={4}>
                {
                    surveyItems.map(({name, desc, cb, type, unit, list}: any, i: number) => {
                        if(isMemoLast && (surveyItems.length-1)===i)  return null;
                        if (cb?.edit) {
                            if(!cb?.toTail)
                                return <React.Fragment key={i}>{ cb.edit(inp, setInp) }</React.Fragment>;
                            else{
                                const aNode=<React.Fragment key={i}>
                                    <Text>{cb?.toTail}：</Text>
                                    { cb.edit(inp, setInp) }
                                </React.Fragment>;
                                toTailNodes.push(aNode);
                            }
                        } else if (type === 'l') return <InputLine key={i} label={desc}>
                            <InputDatalist value={(inp?.[name]) || ''} datalist={list}
                                           onListChange={v => {
                                               setInp({...inp, [name]: v || undefined});
                                           }}/>
                        </InputLine>;
                        else if (type === 'd') return <InputLine key={i} label={desc}>
                            <Input value={inp?.[name] || ''} type='date'
                                   onChange={e => setInp({...inp, [name]: e.currentTarget.value})}/>
                        </InputLine>;
                        else if (type === 'b') return <InputLine key={i} label={desc}>
                            <CheckSwitch checked={inp?.[name] || false}
                                         onChange={e => setInp({...inp, [name]: inp?.[name] ? undefined : true})}/>
                        </InputLine>;
                        else if (type === 'B') return <InputLine key={i} label={desc}>
                            <BlobInputList value={inp?.[name] || ''} datalist={list}
                                           onListChange={v => setInp({...inp, [name]: v || undefined})}/>
                        </InputLine>;
                        else if (type === 'm') return <div key={i}>{desc}:
                            <TextArea value={inp?.[name] || ''} rows={4}
                                      onChange={e => setInp({...inp, [name]: e.currentTarget.value || undefined})}/>
                        </div>;
                        else if (unit) return <InputLine key={i} label={desc}>
                            <SuffixInput value={inp?.[name] || ''}
                                         onSave={txt => setInp({...inp, [name]: txt || undefined})}
                                         type={type === 'n' ? "number" : undefined}>{unit}</SuffixInput>
                        </InputLine>;
                        else return <InputLine label={desc + `:`} key={i}>
                                <Input value={inp?.[name] || ''} type={type === 'n' ? "number" : undefined}
                                       onChange={e => {
                                           setInp({...inp, [name]: e.currentTarget.value || undefined});
                                       }}/>
                            </InputLine>;
                    })
                }
            </LineColumn>
            {toTailNodes}
            { isMemoLast && <>
                {lastAiObj.desc}:
                <TextArea value={inp?.[lastAiObj.name] || ''} rows={5}
                          onChange={e => setInp({...inp, [lastAiObj.name]: e.currentTarget.value || undefined})}/>
             </>
            }
            { children }
            {!alone && show && <>
                <hr/>
                <Text variant="h5">
                    三、检验记录
                </Text>
            </>
            }
        </InspectRecordLayout>
    );
});

